package com.atguigu.gmall.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.user.model.UserInfo;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import com.atguigu.gmall.user.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 用户表 业务实现类
 *
 * @author atguigu
 * @since 2023-01-10
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    //@Autowired
    //private UserInfoMapper userInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户登录
     *
     * @param loginInfo
     * @param request
     * @return
     */
    @Override
    public Result login(UserInfo loginInfo, HttpServletRequest request) {
        //1.验证用户信息是否合法-根据根据用户名密码查询用户记录--注意：数据库中密码为密文
        //1.1 对用户填写密码进行md5加密
        String userPwd = DigestUtils.md5DigestAsHex(loginInfo.getPasswd().getBytes());

        //1.2 根据用户账户+用户填写加密后密码 进行查询
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getLoginName, loginInfo.getLoginName());
        queryWrapper.eq(UserInfo::getPasswd, userPwd);
        UserInfo userInfo = getOne(queryWrapper);
        if (userInfo == null) {
            return Result.fail().message("用户名或者密码错误！");
        }
        //2.如果用户认证通过，将用户信息以及Token存入Redis 设置有限期7天
        //2.1 生成存入redis 令牌UUID
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String redisKey = RedisConst.USER_LOGIN_KEY_PREFIX + uuid;
        //2.2 生成存入redis中用户信息
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId", userInfo.getId());
        jsonObject.put("ip", IpUtil.getIpAddress(request));
        redisTemplate.opsForValue().set(redisKey, jsonObject, RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);

        //3.按照接口文档要求封装响应业务数据{token:"UUID令牌", data:用户信息}
        HashMap<String, Object> data = new HashMap<>();
        data.put("token", uuid);
        data.put("nickName", userInfo.getNickName());
        return Result.ok(data);
    }


    /**
     * 用户退出，将登录后存储在Redis中token删除即可
     *
     * @param token
     */
    @Override
    public void logout(String token) {
        String redisKey = RedisConst.USER_LOGIN_KEY_PREFIX + token;
        redisTemplate.delete(redisKey);
    }
}
